package com.zhugang.week07;

import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

/**
 * @program algorithms
 * @description: topKFrequent
 * @author: chanzhugang
 * @create: 2022/08/02 09:24
 */
public class TopKFrequent2 {

    /**
     * 347 前K个高频元素
     *
     * @param nums
     * @param k
     * @return
     */
    public int[] topKFrequent(int[] nums, int k) {
        // 统计元素出现频率，小顶堆处理前k个
        Map<Integer, Integer> countMap = new HashMap<>();
        for (int num : nums) {
            int count = 1;
            if (countMap.containsKey(num)) {
                count += countMap.get(num);
            }
            countMap.put(num, count);
        }

        PriorityQueue<QElement> minQueue = new PriorityQueue<>((o1, o2) -> o1.count - o2.count);

        countMap.forEach((num, count) -> {
            if (minQueue.size() < k) {
                minQueue.offer(new QElement(num, count));
            } else {
                if (minQueue.peek().count < count) {
                    // 淘汰掉频率低的元素，频率大的加入到小顶堆
                    minQueue.poll();
                    minQueue.offer(new QElement(num, count));
                }
            }
        });

        int[] result = new int[k];
        for (int i = 0; i < k; i++) {
            result[i] = minQueue.poll().val;
        }
        return result;
    }

    private class QElement {
        int val;
        int count;

        public QElement(int val, int count) {
            this.val = val;
            this.count = count;
        }
    }


}